package com.cookor.poi.modules.phy.aop;

import com.alibaba.fastjson.JSON;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class LogAop {
  protected Logger log = LoggerFactory.getLogger(getClass());
  
  @Pointcut("@annotation(com.cookor.poi.modules.phy.annotation.MyLog)")
  public void executeService() {}
  
  @Before("executeService()")
  public void doBefore(JoinPoint joinPoint) throws Throwable {
    ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    if (request == null)
      return; 
    String username = "22";
    try {
      username = "22";
    } catch (Exception e) {
      this.log.info("打印请求参数，用户登陆过期 无法获取请求参数");
    } 
    this.log.info("========================================== Start ==========================================");
    this.log.info("URL            : {}", request.getRequestURL().toString());
    this.log.info("HTTP Method    : {}", request.getMethod());
    this.log.info("IP             : {}", request.getRemoteAddr());
    String queryString = request.getQueryString();
    Object[] args = joinPoint.getArgs();
    String method = request.getMethod();
    String params = "";
    if (args.length > 0)
      if ("POST".equals(method)) {
        params = JSON.toJSONString(request.getParameterMap());
      } else if ("GET".equals(method)) {
        params = queryString;
      }  
    this.log.info("Request Args   : {}", params);
  }
  
  @After("executeService()")
  public void doAfter() throws Throwable {
    this.log.info("=========================================== End ===========================================");
    this.log.info("");
  }
  
  @Around("executeService()")
  public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    long startTime = System.currentTimeMillis();
    Object result = proceedingJoinPoint.proceed();
    this.log.info("Time-Consuming : {} ms", Long.valueOf(System.currentTimeMillis() - startTime));
    return result;
  }
}
